/**
 * 468. 验证IP地址
 * https://leetcode.cn/problems/validate-ip-address/
 */

/**
 * @param {string} queryIP
 * @return {string}
 */
function validIPAddress(queryIP) {
  const codeZero = '0'.charCodeAt(0);
  const codeNine = '9'.charCodeAt(0);
  const codeALower = 'a'.charCodeAt(0);
  const codeFLower = 'f'.charCodeAt(0);
  const codeAUpper = 'A'.charCodeAt(0);
  const codeFUpper = 'F'.charCodeAt(0);

  if (queryIP.includes('.') && queryIP.includes(':')) {
    return 'Neither';
  }

  if (queryIP.includes('.')) {
    const splits = queryIP.split('.');
    if (splits.length !== 4) {
      return 'Neither';
    }
    for (let i = 0; i < splits.length; i += 1) {
      const split = splits[i];
      if (
        !split || split.length > 3
        || (split.length > 1 && split[0] === '0')
      ) {
        return 'Neither';
      }
      for (let j = 0; j < split.length; j += 1) {
        const code = split.charCodeAt(j);
        if (code < codeZero || code > codeNine) {
          return 'Neither';
        }
      }
      if (split > '255') {
        return 'Neither';
      }
    }
    return 'IPv4';
  }

  if (queryIP.includes(':')) {
    const splits = queryIP.split(':');
    if (splits.length !== 8) {
      return 'Neither';
    }
    for (let i = 0; i < splits.length; i += 1) {
      const split = splits[i];
      if (!split || split.length > 4) {
        return 'Neither';
      }
      for (let j = 0; j < split.length; j += 1) {
        const code = split.charCodeAt(j);
        if (!(
          (code >= codeZero && code <= codeNine)
          || (code >= codeALower && code <= codeFLower)
          || (code >= codeAUpper && code <= codeFUpper)
        )) {
          return 'Neither';
        }
      }
    }
    return 'IPv6';
  }

  return 'Neither';
}

console.log(validIPAddress('192.168.1.1') === 'IPv4');
console.log(validIPAddress('192.168.1.0') === 'IPv4');
console.log(validIPAddress('192.168.01.1') === 'Neither');
console.log(validIPAddress('192.168.1.00') === 'Neither');
console.log(validIPAddress('192.168.1.00') === 'Neither');
console.log(validIPAddress('2001:0db8:85a3:0000:0000:8a2e:0370:7334') === 'IPv6');
console.log(validIPAddress('2001:db8:85a3:0:0:8A2E:0370:7334') === 'IPv6');
console.log(validIPAddress('2001:0db8:85a3::8A2E:037j:7334') === 'Neither');
console.log(validIPAddress('02001:0db8:85a3:0000:0000:8a2e:0370:7334') === 'Neither');
console.log(validIPAddress('172.16.254.1') === 'IPv4');
console.log(validIPAddress('2001:0db8:85a3:0:0:8A2E:0370:7334') === 'IPv6');
console.log(validIPAddress('256.256.256.256') === 'Neither');
